package com.yssw.util;

import com.yssw.config.ImageManagerImpl;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @Author KnockingFarmers
 * @Date 2023/3/31 15:00
 * @PackageName:com.yssw.util
 * @ClassName: FileUtil
 * @Description: TODO
 * @Version 1.0
 */
@Slf4j
@Component
public class FileUtil {



    @Autowired
    private ImageManagerImpl imageManager;

    public  String word2007ToHtml(MultipartFile file) throws IOException {
        String html = null;
        if (file.isEmpty() || file.getSize() <= 0) {
            log.error("Sorry File does not Exists!");
            return null;
        } else {
            /* 判断是否为docx文件 */
            if (Objects.requireNonNull(file.getOriginalFilename()).endsWith(".docx") || file.getOriginalFilename().endsWith(".DOCX")
            ||Objects.requireNonNull(file.getOriginalFilename()).endsWith(".doc") || file.getOriginalFilename().endsWith(".DOC")) {
                // 1)加载word文档生成XWPFDocument对象
                @Cleanup FileInputStream in = (FileInputStream) file.getInputStream();
                XWPFDocument document = new XWPFDocument(in);
                // 2)解析XHTML配置（这里设置IURIResolver来设置图片存放的目录）
                XHTMLOptions options = XHTMLOptions.create();
                //3.将word中图片保存到本地中
//                ImageManager im=new ImageManager(new File(imgSubDir),imgSubDir);
                options.setImageManager(imageManager);

                options.setIgnoreStylesIfUnused(false);
                options.setFragment(true);
                // 3)将XWPFDocument转换成XHTML
                @Cleanup ByteArrayOutputStream baos = new ByteArrayOutputStream();
                XHTMLConverter.getInstance().convert(document, baos, options);
                html = new String(baos.toByteArray(), StandardCharsets.UTF_8);
                log.info(html);

            } else {
                System.out.println("Enter only as MS Office 2007+ files");
                throw new RuntimeException("word文档必须以.docx结尾");
            }
        }
        return html;
    }


    /**
     * 将MultipartFile转换为File
     *
     *
     * @param outFilePath 参数
     * @param multiFile 参数
     * @return 执行结果
     */
    public static File multipartFileToFile(String outFilePath, MultipartFile multiFile) {
        // 获取文件名
        if (null == multiFile) {
            return null;
        }
        String fileName = multiFile.getOriginalFilename();
        if (null == fileName) {
            return null;
        }
        try {
            File toFile;
            InputStream ins;
            ins = multiFile.getInputStream();
            //指定存储路径
            toFile = new File(outFilePath.concat(File.separator).concat(multiFile.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            return toFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private static void inputStreamToFile(InputStream ins, File file) {
        try (OutputStream os = new FileOutputStream(file)) {
            int bytesRead;
            int bytes = 8192;
            byte[] buffer = new byte[bytes];
            while ((bytesRead = ins.read(buffer, 0, bytes)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





}
